// $Id: XPathUtils.java 8 2011-09-08 13:36:54Z huijzer@gmail.com $
package lime.common;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XPathUtils {

	private XPathUtils() {
		// Empty
	}

	public static Boolean evaluateAsBoolean(final String xpathExpression, final Node node)
			throws XPathExpressionException {

		XPathFactory factory = XPathFactory.newInstance();
		XPath xpath = factory.newXPath();
		Boolean result = (Boolean) xpath.evaluate(xpathExpression, node, XPathConstants.BOOLEAN);

		return result;
	}

	public static Integer evaluateAsInteger(final String xpathExpression, final Node node)
			throws XPathExpressionException {

		XPathFactory factory = XPathFactory.newInstance();
		XPath xpath = factory.newXPath();
		Integer result = (Integer) xpath.evaluate(xpathExpression, node, XPathConstants.NUMBER);

		return result;
	}
	
	public static Node evaluateAsNode(final String xpathExpression, final Node node)
			throws XPathExpressionException {

		XPathFactory factory = XPathFactory.newInstance();
		XPath xpath = factory.newXPath();
		Node result = (Node) xpath.evaluate(xpathExpression, node, XPathConstants.NODE);

		return result;
	}
	
	public static NodeList evaluateAsNodeList(final String xpathExpression, final Node node)
			throws XPathExpressionException {

		XPathFactory factory = XPathFactory.newInstance();
		XPath xpath = factory.newXPath();
		NodeList result = (NodeList) xpath.evaluate(xpathExpression, node, XPathConstants.NODESET);

		return result;
	}
	
	public static String evaluateAsString(final String xpathExpression, final Node node)
			throws XPathExpressionException {

		XPathFactory factory = XPathFactory.newInstance();
		XPath xpath = factory.newXPath();
		String result = (String) xpath.evaluate(xpathExpression, node, XPathConstants.STRING);

		return result;
	}
}
